package com.hdyg.csc.util;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class StringUtil {

    /**
     * 字符串前面补 0
     * eg amount = 1234
     * length = 6
     * return 001234
     *
     * @param amount 字符串
     * @param lenght 长度
     * @return
     */
    public static String getAmount(String amount, int lenght) {
        String str2 = "";
        for (int i = 0; i < (lenght - amount.length()); i++) {
            str2 = str2 + "0";
        }
        str2 = str2 + amount;
        return str2;
    }

    /**
     * 字符串后面补 0
     * eg amount = 1234
     * length = 6
     * return 123400
     *
     * @param amount 字符串
     * @param lenght 长度
     * @return
     */
    public static String getZero(String amount, int lenght) {
        String str2 = "";
        for (int i = 0; i < (lenght - amount.length()); i++) {
            str2 = str2 + "0";
        }
        str2 = amount + str2;
        return str2;
    }

    /**
     * MD5加密
     *
     * @param resultMap map
     * @param key       key
     * @return
     */
//    public static String Md5Str(Map<String, String> resultMap, String key) {
//        String responseString = ParameterUtils.getRequestQueryString(resultMap, key);
//        String sign = Md5Encrypt.md5(responseString);
//        return sign;
//    }

    /**
     * 获取随机数
     *
     * @return
     */
    public static String random() {
//        String s = null;
//        String str = null;
//        try {
//            str = DateUtils.getCurrDate("yyyy-MM-dd HH:mm:ss");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        s = DateUtils.timeToStamp(str, "yyyy-MM-dd HH:mm:ss");
//        LogUtils.d("时间戳：" + s + ",时间：" + str);
//        return s;
        String time =String.valueOf(System.currentTimeMillis()/1000);
        return time;
    }


    public static String generateCheckValue(byte[] src) {
        System.out.println("src : " + src.toString());
        byte b = 0x00;
        for (int i = 0; i < src.length; i++) {
            b = (byte) (b ^ src[i]);
        }

        String byte2hex = byte2hex(new byte[]{b});
        System.out.println("byte2hex : " + byte2hex);
        return byte2hex;
    }

    /**
     * 二进制转字符串
     *
     * @param src
     * @return
     */
    public static String byte2hex(byte[] src) {
        final String HEX = "0123456789abcdef";
        StringBuilder sb = new StringBuilder(src.length * 2);
        for (byte b : src) {
            sb.append(HEX.charAt((b >> 4) & 0x0f));
            sb.append(HEX.charAt(b & 0x0f));
        }
        return sb.toString();
    }

    /**
     * @param content 生成二维码传递的内容
     * @param width   二维码 宽
     * @param height  二维码 高
     * @return
     */
    public static Bitmap generateQRCodeBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存图片到本地的方法
     *
     * @param context 上下文
     * @param bmp     图片
     * @param id      res下的图片ID
     * @return 图片存放地址
     */
    public static String saveImageToGallery(Context context, Bitmap bmp, int id) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");//存放的文件夹
        String fileName = "logo.jpg";//存放的文件名
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //判断bmp是否为空  是空的话 就执行本地图片转bitmap
            if (bmp == null) {
                Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } else {
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            }

            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        String path = Environment.getExternalStorageDirectory() + "/Boohee/" + fileName;
        Log.d("czb", "图片存放地址============" + path);
        return path;

    }

    /**
     * 获取缓存大小
     *
     * @param context
     * @return
     * @throws Exception
     */
    public static String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    /**
     * 清除缓存
     *
     * @param context
     */
    public static void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(context.getExternalCacheDir());
        }
    }

    //清除缓存调用的子方法
    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 获取文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "Byte";
            return "0K";
        }
        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }
        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    /**
     * dpתpx
     *
     * @param context
     * @param dp
     * @return
     */
    public static int dp2px(Context context, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dp, context.getResources().getDisplayMetrics());
    }

    /**
     * 获取屏幕宽度
     *
     * @param context 上下文
     * @return 屏幕宽度
     */
    public static int getWindowWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 获取屏幕高度
     *
     * @param context 上下文
     * @return 屏幕高度
     */
    public static int getWindowHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 手机号用****号隐藏中间数字
     *
     * @param phone
     * @return
     */
    public static String settingPhone(String phone) {
        String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phone_s;
    }

    /**
     * 验证是否有安装QQ
     *
     * @param context 上下文
     * @return
     */
    //跳转例子
//	if (checkApkExist(this, "com.tencent.mobileqq")){
//		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin="+qqNum+"&version=1")));
//	}else{
//		Toast.makeText(this,"本机未安装QQ应用",Toast.LENGTH_SHORT).show();
//	}
    public static boolean checkApkExist(Context context) {
        String packageName = "com.tencent.mobileqq";//QQ包名
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 复制文本到剪贴板
     *
     * @param txt     文本内容
     * @param context 上下文对象
     */
    public static void copyTextMethod(Context context, String txt) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(txt);
        Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 跳转到拨打电话 并传递电话号码
     *
     * @param context 上下文对象
     * @param number  电话号码
     */
    public static void intentCallPhone(Context context, String number) {
        Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));//跳转到拨号界面，同时传递电话号码
        context.startActivity(dialIntent);
    }

    /**
     * 文字变色
     * @param textView view
     * @param text 显示的文字
     * @param color 需要变色的颜色
     * @param length 从什么长度开始变色
     */
    public static void setTextView(TextView textView,String text, int color,int length){
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new ForegroundColorSpan(color), length, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannableString);
    }

}
